<template>
    <div class="tempbigbox">
        <div class="page-content">
            <h3 style="margin-bottom: 20px">提现记录</h3>
            <el-form :model="searchForm" ref="searchFormRef" label-width="100px" style="margin-top: 20px">
                <el-row :gutter="24">
                    <el-col :span="6">
                        <el-form-item label="推广员信息：" prop="name">
                            <el-input v-model="searchForm.name" placeholder="请输入推广员信息" @blur="getData" clearable />
                        </el-form-item>
                    </el-col>
                    <!-- <form-input label="推广员信息" prop="name" v-model="searchForm.name" /> -->
                    <el-col :span="6">
                        <el-form-item label="提现状态" prop="withdrawalStatusList">
                            <el-select v-model="searchForm.withdrawalStatusList" placeholder="请选择状态" multiple clearable
                                @change="getData">
                                <el-option v-for="item in withdrawalOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <div class="databox">
                            <label class="el-form-item__label">创建时间：</label>
                            <el-date-picker label="创建时间：" v-model="datavalue" type="datetimerange"
                                start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss"
                                date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" @change="timeChange" />
                        </div>
                    </el-col>
                    <!-- <el-button style="margin-left: 20px" @click="getData">搜索</el-button>
                    <el-button style="margin-left: 20px" @click="reset">重置</el-button> -->
                    <el-button type="primary" :disabled="!multipleSelection.length" @click="handleBatchApprove"
                        :loading="batchApproveLoading">批量通过</el-button>
                    <el-button type="danger" :disabled="!multipleSelection.length" @click="openBatchRefuseDialog"
                        :loading="batchRefuseLoading" style="margin-left: 10px;">批量拒绝</el-button>
                </el-row>
            </el-form>
            <art-table :data="tableData" selection :currentPage="pageNum" :pageSize="pageSize" :total="pagetotal"
                @current-change="currentChange" @size-change="sizeChange" @selection-change="handleSelectionChange">
                <template #default>
                    <el-table-column label="提现人信息" prop="name" #default="scope" width="300px">
                        <div class="user" style="display: flex; align-items: center">
                            <div>
                                <p class="user-name">{{ scope.row.name }}</p>
                                <p class="email">ID:{{ scope.row.accountNo }}</p>
                            </div>
                        </div>
                    </el-table-column>
                    <el-table-column label="提现编号" prop="withdrawalNo" align="center" />
                    <el-table-column label="第三方编号" prop="thirdPartyNo" align="center" />
                    <el-table-column label="提现类型" prop="withdrawalType" align="center" #default="scope">
                        {{ scope.row.withdrawalType === '01' ? '微信' : scope.row.withdrawalType ===
                            '02' ? '支付宝' : '银行卡' }}
                    </el-table-column>
                    <el-table-column label="提现金额（元）" prop="price" align="center" #default="scope">
                        {{ scope.row.price / 100 }}
                    </el-table-column>
                    <el-table-column label="手续费（元）" prop="feePrice" align="center" #default="scope">
                        {{ scope.row.feePrice / 100 }}
                    </el-table-column>
                    <el-table-column label="到账金额（元）" prop="actualPrice" align="center" #default="scope">
                        {{ scope.row.actualPrice / 100 }}
                    </el-table-column>
                    <el-table-column label="提现状态" prop="withdrawalStatus" :filters="[
                        { text: '待审核', value: '0' },
                        { text: '审核通过', value: '1' },
                        { text: '已打款', value: '2' },
                        { text: '审核驳回', value: '3' },
                        { text: '打款失败', value: '4' }
                    ]" :filter-method="filterTag" filter-placement="bottom-end" align="center">
                        <template #default="scope">
                            <el-tag :type="getTagType(scope.row.withdrawalStatus)">
                                {{ scope.row.withdrawalStatus < 5 ? buildTagText(scope.row.withdrawalStatus) : '' }}
                                    </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="申请时间" prop="createTime" sortable align="center" />
                    <el-table-column fixed="right" label="操作" width="400px" align="center">
                        <template #default="scope">
                            <div>
                                <el-button type="primary" size="default" plain @click="toExamine(scope.row, 1)"
                                    v-if="scope.row.withdrawalStatus === 0">通过</el-button>
                                <el-button type="danger" size="default" plain @click="refuse(scope.row)"
                                    style="margin-right: 10px;" v-if="scope.row.withdrawalStatus === 0">拒绝</el-button>
                                <el-button type="success" size="default" plain
                                    @click="openManualPaymentDialog(scope.row, 1)" style="margin-right: 10px;"
                                    v-if="scope.row.withdrawalStatus === 0 || scope.row.withdrawalStatus === 4">手动打款</el-button>
                                <el-button type="success" size="default" plain
                                    @click="openManualPaymentDialog(scope.row, 2)" style="margin-right: 10px;"
                                    v-if="scope.row.withdrawalStatus === 2">打款详情</el-button>
                                <button-table type="edit" @click="editRules(scope.row)"
                                    v-if="scope.row.withdrawalStatus === 3" />
                            </div>
                        </template>
                    </el-table-column>
                </template>
            </art-table>
        </div>
        <!-- 批量拒绝弹窗 -->
        <el-dialog v-model="batchRefuseDialog" title="批量拒绝" width="30%" :close-on-click-modal="false">
            <el-input v-model="batchRejectReason" type="textarea" :rows="4" placeholder="请输入拒绝原因" />
            <template #footer>
                <el-button @click="batchRefuseDialog = false">取消</el-button>
                <el-button type="primary" :loading="batchRefuseLoading" @click="handleBatchRefuse">确定</el-button>
            </template>
        </el-dialog>
        <!-- 单条拒绝弹窗 -->
        <el-dialog v-model="refuseDialog" title="填写拒绝原因" width="30%" :close-on-click-modal="false">
            <el-input v-model="formData.auditReason" type="textarea" :rows="4" placeholder="请输入拒绝原因" />
            <template #footer>
                <el-button @click="refuseDialog = false">取消</el-button>
                <el-button type="primary" @click="toExamine(refuseList, 2)">确定</el-button>
            </template>
        </el-dialog>
        <!-- 手动打款弹窗 -->
        <el-dialog v-model="manualPaymentDialogVisible" :title="drawnState === 1 ? '手动打款' : '打款详情'" width="700px"
            :close-on-click-modal="false">
            <div class="manual-payment-dialog-body">
                <div class="manual-payment-left">
                    <el-form :model="manualPaymentForm" label-width="100px" class="manual-payment-form">
                        <el-form-item label="账户类型：">
                            <span>
                                {{ manualPaymentForm.bankType === '01' ? '微信' : manualPaymentForm.bankType
                                    === '02'
                                    ? '支付宝' : '银行卡' }}
                            </span>
                        </el-form-item>
                        <el-form-item label="应打款金额：">
                            <span>{{ actualPrice / 100 }}</span>（元）
                        </el-form-item>
                        <el-form-item label="账户实名：">
                            <span>{{ manualPaymentForm.accountName }}</span>
                        </el-form-item>
                        <el-form-item label="账户号码：">
                            <span>{{ manualPaymentForm.accountNo }} </span>
                        </el-form-item>
                        <el-form-item label="身份证号：">
                            <span>{{ manualPaymentForm.idCardNo }} </span>
                        </el-form-item>
                        <el-form-item label="预留手机号：">
                            <span>{{ manualPaymentForm.phone }}</span>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="manual-payment-right">
                    <el-form :model="manualPaymentForm" label-width="100px" class="manual-payment-form">
                        <el-form-item label="银行名称：" v-if="manualPaymentForm.bankType === '03'">
                            <span>{{ manualPaymentForm.bankName || '暂无信息' }} </span>
                        </el-form-item>
                        <el-form-item label="银行编码：" v-if="manualPaymentForm.bankType === '03'">
                            <span>{{ manualPaymentForm.bankCode || '暂无信息' }} </span>
                        </el-form-item>
                        <el-form-item label="支行名称：" v-if="manualPaymentForm.bankType === '03'">
                            <span>{{ manualPaymentForm.branchName || '暂无信息' }} </span>
                        </el-form-item>
                        <el-form-item label="收款码：" v-else>
                            <el-image v-if="manualPaymentForm.qrCodeUrl" class="skmImg" preview-teleported
                                :preview-src-list="[manualPaymentForm.qrCodeUrl]" hide-on-click-modal
                                :src="manualPaymentForm.qrCodeUrl"></el-image>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <template #footer>
                <el-button @click="manualPaymentDialogVisible = false">取消</el-button>
                <el-button type="primary" :loading="manualPaymentLoading" @click="handleManualPayment"
                    v-if="drawnState === 1">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useSettingStore } from '@/store/modules/setting'
import { useCommon } from '@/composables/useCommon'
import { FormInstance } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import {
    editWithdrawalRecord,
    withdrawalRecord,
    paymentInformation,
    editPaymentInfor
} from '@/api/marketing'
import { useUserStore } from '@/store/modules/user'

// 新增：批量操作相关
const multipleSelection = ref<any[]>([])
const batchApproveLoading = ref(false)
const batchRefuseLoading = ref(false)
const batchRefuseDialog = ref(false)
const batchRejectReason = ref('')

const dialogVisible = ref(false)
const withdrawalTypeList = ref([{ label: '微信', value: '01' }, { label: '支付宝', value: '02' }, { label: '银行卡', value: '03' }])

// 手动打款弹窗相关
const manualPaymentDialogVisible = ref(false)
const manualPaymentLoading = ref(false)
const manualPaymentForm = reactive<any>({
    id: '',
    bankType: '',
    accountName: '',
    accountNo: '',
    bankName: '',
    bankCode: '',
    branchName: '',
    idCardNo: '',
    phone: ''
})

const withdrawalid = ref('')
const actualPrice = ref<any>('')
const drawnState = ref()
const openManualPaymentDialog = async (row: any, state: any) => {
    withdrawalid.value = row.id
    actualPrice.value = row.actualPrice
    drawnState.value = state
    console.log(drawnState.value, "drawnState.value====");
    const res = await paymentInformation({ id: row.id })
    if (res.code === '00000') {
        manualPaymentForm.bankType = res.data.bankType
        manualPaymentForm.id = res.data.id
        manualPaymentForm.accountName = res.data.accountName
        manualPaymentForm.accountNo = res.data.accountNo
        manualPaymentForm.bankName = res.data.bankName
        manualPaymentForm.bankCode = res.data.bankCode
        manualPaymentForm.branchName = res.data.branchName
        manualPaymentForm.idCardNo = res.data.idCardNo
        manualPaymentForm.phone = res.data.phone
        manualPaymentForm.qrCodeUrl = res.data.qrCodeUrl
        manualPaymentDialogVisible.value = true
    } else {
        ElMessage.error(res.msg)
    }
}

function handleManualPayment() {
    ElMessageBox.confirm(
        `是否确认手动打款，打款金额：<span style="text-decoration:underline">${actualPrice.value / 100}（元）</span>`,
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
        }
    ).then(() => {
        PaymentMoney()
    })
}

const PaymentMoney = async () => {
    manualPaymentLoading.value = true
    try {
        const params = {
            withdrawalid: withdrawalid.value,
            bankid: manualPaymentForm.id
        }
        const res = await editPaymentInfor(params)
        if (res.code === '00000') {
            ElMessage.success('手动打款成功')
            manualPaymentDialogVisible.value = false
            getData()
        } else {
            ElMessage.error(res.msg || '手动打款失败')
        }
    } catch (e) {
        ElMessage.error('网络异常，请稍后重试')
    } finally {
        manualPaymentLoading.value = false
    }
}

// 选择变化
const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val
}

// 批量通过
const handleBatchApprove = async () => {
    if (!multipleSelection.value.length) return
    batchApproveLoading.value = true
    try {
        // 只处理待审核的
        const ids = multipleSelection.value.filter(item => item.withdrawalStatus === 0).map(item => item.id)
        if (!ids.length) {
            ElMessage.warning('请选择待审核的记录进行批量通过')
            return
        }
        const res = await editWithdrawalRecord({
            idList: ids,
            promoterStatus: 1
        })
        if (res.code === '00000') {
            ElMessage.success('批量通过成功')
            getData()
        }
    } catch (e) {
        ElMessage.error('网络异常，请稍后重试')
    } finally {
        batchApproveLoading.value = false
    }
}

// 打开批量拒绝弹窗
const openBatchRefuseDialog = () => {
    if (!multipleSelection.value.length) return
    batchRejectReason.value = ''
    batchRefuseDialog.value = true
}

// 批量拒绝
const handleBatchRefuse = async () => {
    if (!multipleSelection.value.length) return
    if (!batchRejectReason.value) {
        ElMessage.warning('请输入拒绝原因')
        return
    }
    batchRefuseLoading.value = true
    try {
        // 只处理待审核的
        const ids = multipleSelection.value.filter(item => item.withdrawalStatus === 0).map(item => item.id)
        if (!ids.length) {
            ElMessage.warning('请选择待审核的记录进行批量拒绝')
            batchRefuseLoading.value = false
            return
        }
        // 假设editWithdrawalRecord支持批量
        const res = await editWithdrawalRecord({
            idList: ids,
            withdrawalStatus: 3,
            auditReason: batchRejectReason.value
        })
        if (res.code === '00000') {
            ElMessage.success('批量拒绝成功')
            batchRefuseDialog.value = false
            getData()
        } else {
            ElMessage.error(res.msg || '批量拒绝失败')
        }
    } catch (e) {
        ElMessage.error('网络异常，请稍后重试')
    } finally {
        batchRefuseLoading.value = false
    }
}

const settingStore = useSettingStore()
const currentGlopTheme = computed(() => settingStore.systemThemeType)
const refuseDialog = ref(false)

watch(currentGlopTheme, () => {
    settingStore.reload()
})

useCommon().scrollToTop()

const refuseList = ref<any>({})
const refuse = (e: any) => {
    refuseDialog.value = true
    refuseList.value = e
}

const editRules = (e: any) => {
    refuseDialog.value = true
    refuseList.value = e
    formData.auditReason = e.auditReason
}

const withdrawalOptions = [
    {
        value: '0',
        label: '待审核'
    },
    {
        value: '1',
        label: '审核通过'
    },
    {
        value: '2',
        label: '已打款'
    },
    {
        value: '3',
        label: '审核驳回'
    },
    {
        value: '4',
        label: '打款失败'
    }
]

const searchForm = reactive<any>({
    name: '',
    bindPhone: '',
    queryStartTime: '',
    queryEndTime: '',
    levelId: '',
    withdrawalStatusList: []
})
const formData = reactive({
    name: '',
    parentId: '',
    leaderMobile: '',
    meMobile: '',
    id: '',
    rejectReason: '',
    auditReason: ''
})

const searchFormRef = ref<FormInstance>()

const tableData = ref([])
const pagetotal = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const tableLoading = ref(false)

const filterTag = (value: string, row: any) => {
    return row.status === value
}

const getTagType = (status: number) => {
    switch (status) {
        case 0:
            return 'info'
        case 1:
            return 'primary'
        case 2:
            return 'primary'
        case 3:
            return 'danger'
        case 4:
            return 'warning'
    }
}

const buildTagText = (status: number) => {
    let text = ''
    if (status === 0) {
        text = '待审核'
    } else if (status === 1) {
        text = '审核通过'
    } else if (status === 2) {
        text = '已打款'
    } else if (status === 3) {
        text = '审核驳回'
    } else {
        text = '打款失败'
    }
    return text
}

const formatDate = (date: string) => {
    return new Date(date)
        .toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        })
        .replace(/\//g, '-')
}

const datavalue = ref('')
const timeChange = (e: any) => {
    if (e) {
        searchForm.queryStartTime = formatDate(e[0])
        searchForm.queryEndTime = formatDate(e[1])
    } else {
        searchForm.queryStartTime = ''
        searchForm.queryEndTime = ''
    }
    getData()
}

const promoterStatus = ref([1, 3])

const filterEmptyValues = (obj: any) => {
    const result: any = {}
    for (const key in obj) {
        if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
            result[key] = obj[key]
        }
    }
    return result
}

const getData = async () => {
    try {
        tableLoading.value = true
        const params = filterEmptyValues(searchForm)
        // 确保 withdrawalStatusList 传递为数组
        if (!Array.isArray(params.withdrawalStatusList)) {
            params.withdrawalStatusList = []
        }
        const { code, data } = await withdrawalRecord({
            pageNum: pageNum.value,
            pageSize: pageSize.value,
            ...params
        })
        if (code === '00000') {
            tableData.value = data.list
            pagetotal.value = data.total
        }
    } catch (e) {
    } finally {
        tableLoading.value = false
    }
}

const reset = () => {
    searchForm.name = ''
    searchForm.levelId = ''
    searchForm.queryStartTime = ''
    searchForm.queryEndTime = ''
    searchForm.bindPhone = ''
    searchForm.withdrawalStatusList = []
    datavalue.value = ''
}

const currentChange = (val: number) => {
    pageNum.value = val
    getData()
}

const sizeChange = (val: number) => {
    pageSize.value = val
    pageNum.value = 1
    getData()
}

const examineLoading = ref(false)
const toExamine = async (e: any, status: number) => {
    try {
        examineLoading.value = true
        if (!formData.auditReason && status !== 1) {
            ElMessage.warning('请输入拒绝原因')
            return
        }
        let params = {
            idList: [e.id],
            withdrawalStatus: status === 1 ? 1 : 3,
            auditReason: formData.auditReason
        }
        const res = await editWithdrawalRecord(filterEmptyValues(params))
        if (res.code === '00000') {
            ElMessage.success(status === 1 ? '通过成功' : '拒绝成功')
            if (status === 2) {
                refuseDialog.value = false
            }
            getData()
        } else {
            ElMessage.error(res.msg || '操作失败')
        }
    } catch (err) {
        ElMessage.error('网络异常，请稍后重试')
    } finally {
        examineLoading.value = false
    }
}

onMounted(() => {
    getData()
})
</script>

<style lang="scss" scoped>
.console {
    padding-bottom: 15px;

    :deep(.card-header) {
        display: flex;
        justify-content: space-between;
        padding: 20px 25px 5px 0;

        .title {
            h4 {
                font-size: 18px;
                font-weight: 500;
                color: var(--art-text-gray-800);
            }

            p {
                margin-top: 3px;
                font-size: 13px;

                span {
                    margin-left: 10px;
                    color: #52c41a;
                }
            }
        }
    }

    // 主标题
    :deep(.box-title) {
        color: var(--art-gray-900) !important;
    }

    // 副标题
    :deep(.subtitle) {
        color: var(--art-gray-600) !important;
    }

    :deep(.card-list li),
    .region,
    .dynamic,
    .bottom-wrap {
        background: var(--art-main-bg-color);
        border-radius: calc(var(--custom-radius) + 4px) !important;
    }

    .column {
        display: flex;
        justify-content: space-between;
        margin-top: var(--console-margin);
        background-color: transparent !important;
    }

    .bottom-wrap {
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        height: 300px;
        padding: 20px;
        margin-top: var(--console-margin);
        background: var(--art-main-bg-color);

        h2 {
            margin-top: 10px;
            font-size: 20px;
            font-weight: 500;
        }

        p {
            margin-top: 5px;
            font-size: 14px;
            color: var(--art-gray-600);
        }

        .button-wrap {
            display: flex;
            flex-wrap: wrap;
            width: 600px;
            margin-top: 35px;

            .btn {
                display: flex;
                justify-content: space-between;
                width: 240px;
                height: 50px;
                padding: 0 15px;
                margin: 0 15px 15px 0;
                font-size: 14px;
                line-height: 50px;
                color: var(--art-gray-800);
                text-align: center;
                cursor: pointer;
                background: var(--art-bg-color);
                border-radius: calc(var(--custom-radius) / 2 + 2px) !important;
                transition: all 0.3s;

                &:hover {
                    box-shadow: 0 5px 10px rgb(0 0 0 / 5%);
                    transform: translateY(-4px);
                }
            }
        }
    }
}

.page-content {
    width: 100%;
    height: 100%;

    .user {
        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 6px;
        }

        >div {
            margin-left: 10px;

            .user-name {
                font-weight: 500;
                color: var(--art-text-gray-800);
            }
        }
    }
}

.manual-payment-dialog-body {
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .manual-payment-left,
    .manual-payment-right {
        width: 48%;
    }

    .manual-payment-form {
        padding: 10px 0;
    }
}

.skmImg {
    width: 180px;
    height: 180px;
}
</style>